package com.jsy.oauth.config;

import com.jsy.oauth.util.JwtToken;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 在认证微服务中编写拦截器，对调用Feign之前都生产特殊令牌并携带到微服务中
 */
@Component
public class FeignOauthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //生成特殊令牌（里面包含管理员角色）
        String token = JwtToken.adminJwt();
        //添加到header
        requestTemplate.header("Authorization","bearer"+token);
        //顺带把其它头部的信息也携带过去
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            //获取request
            HttpServletRequest request = requestAttributes.getRequest();
            //获取头部信息
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                //头部属性名
                String name = headerNames.nextElement();
                //头部属性值
                String value = request.getHeader(name);
                //设置头部属性
                requestTemplate.header(name,value);
            }

        }

    }
}
